﻿using System;
using System.Text;
using System.Collections;
using System.Collections.Specialized;
using System.Configuration;
using System.Web;
using System.Globalization;
using System.Text.RegularExpressions;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Xml;
//using SWFToImage;

namespace Tomato.Text
{
    public class WebUtils
    {

        //将xml对象内容字符串转换为DataSet
        public static DataSet ConvertXMLToDataSet(string xmlData)
        {
            StringReader stream = null;
            XmlTextReader reader = null;
            try
            {
                DataSet xmlDS = new DataSet();
                stream = new StringReader(xmlData);
                //从stream装载到XmlTextReader
                reader = new XmlTextReader(stream);
                xmlDS.ReadXml(reader);
                return xmlDS;
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (reader != null) reader.Close();
            }
        }

        /// <summary>
        /// 查询EXCEL电子表格添加到DATASET2011-4-6
        /// </summary>
        /// <param name="filenameurl">服务器路径</param>
        /// <param name="table">表名</param>
        /// 
        /// <returns>更多内容请访问：www.hhaspx.com</returns>
        /// 红河ASP.NET(C#)学习网包含ASP.NET 教程,c#教程,Photoshop,ps教程,网页制作,图片素材,SEO优化

        public static DataSet ExecleDs(string filenameurl, string table)
        {
            string strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + filenameurl + ";Extended Properties='Excel 8.0; HDR=YES; IMEX=1'";
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();
            DataSet ds = new DataSet();
            OleDbDataAdapter odda = new OleDbDataAdapter("select * from [Sheet1$]", conn);
            odda.Fill(ds, table);
            return ds;
        }

        #region html获取图片地址
        //返回单个路径

        public static string GetImgUrl(string HTMLStr)
        {
            string str = string.Empty;
            //string sPattern = @"^<img\s+[^>]*>";
            Regex r = new Regex(@"<img\s+[^>]*\s*src\s*=\s*([']?)(?<url>\S+)'?[^>]*>",
            RegexOptions.Compiled);
            Match m = r.Match(HTMLStr.ToLower());
            if (m.Success)
                str = m.Result("${url}");
            str = str.Replace("\"", "");
            return str;
        }

        public static string GetFlvOrSwfUrl(string HTMLStr)
        {
            string str = string.Empty;
            //string sPattern = @"^<img\s+[^>]*>";
            Regex r = new Regex(@"<embed\s+[^>]*\s*src\s*=\s*([']?)(?<url>\S+)'?[^>]*>",
            RegexOptions.Compiled);
            Match m = r.Match(HTMLStr.ToLower());
            if (m.Success)
                str = m.Result("${url}");
            str = str.Replace("\"", "");
            return str;
        }

        public static string GetAHtmlUrl(string HTMLStr)
        {
            string str = string.Empty;
            //string sPattern = @"^<img\s+[^>]*>";
            Regex r = new Regex(@"<a\s+[^>]*\s*href\s*=\s*([']?)(?<url>\S+)'?[^>]*>",
            RegexOptions.Compiled);
            Match m = r.Match(HTMLStr.ToLower());
            if (m.Success)
                str = m.Result("${url}");
            str = str.Replace("\"", "");
            return str;
        }

        //public static bool isFlvOrSwfFile(string sFileName)
        //{
        //    bool xx = false; //default the "sFileName" is not a .exe or .dll file; 

        //    FileStream fs = new FileStream(sFileName, FileMode.Open, FileAccess.Read);
        //    BinaryReader r = new BinaryReader(fs);

        //    string bx = "";
        //    byte buffer;
        //    try
        //    {
        //        buffer = r.ReadByte();
        //        bx = buffer.ToString();
        //        buffer = r.ReadByte();
        //        bx = bx + buffer.ToString();
        //    }
        //    catch
        //    {

        //    }

        //    r.Close();
        //    fs.Close();
        //    if (bx == "7790" || bx == "8297" || bx == "8075")//7790:exe 8297:rar 8075:pk 
        //    {
        //        xx = true;
        //    }

        //    return xx;

        //} 



        //返回多个路径的情况

        //注意：此方法返回的路径中 带有引号 要去掉才是 返回的准确的路径
        public static StringBuilder MyGetImgUrl(string text)
        {
            StringBuilder str = new StringBuilder();
            string pat = @"<img\s+[^>]*\s*src\s*=\s*([']?)(?<url>\S+)'?[^>]*>";

            Regex r = new Regex(pat, RegexOptions.Compiled);

            Match m = r.Match(text.ToLower());
            //int matchCount = 0;
            while (m.Success)
            {
                Group g = m.Groups[2];
                str.Append(g).Append(",");
                m = m.NextMatch();
            }
            str = str.Replace("\"", "");
            return str;
        }

        /// <summary>
        /// 自主更新的FLASH的截图部分
        /// </summary>
        /// <param name="FlashFilePath">FLASH文件路径</param>
        /// <param name="FileBaseName">预览图路径</param>
        public static string CatchSWFImg(string FlashFilePath, string PicFilePath)
        {
            if (System.IO.File.Exists(FlashFilePath))
            {
                //SWFToImageObjectClass swf = new SWFToImageObjectClass();
                //swf.InitLibrary("demo", "demo");
                //swf.InputSWFFileName = FlashFilePath;
                //swf.ImageOutputType = SWFToImage.TImageOutputType.iotJPG;
                //swf.Execute_Begin();

                //swf.ImageWidth = 150;
                //swf.ImageHeight = 110;

                //Random rnd = new Random();
                //swf.FrameIndex = rnd.Next(swf.FramesCount);
                //swf.Execute_GetImage();
                //swf.SaveToFile(PicFilePath);
                //swf.Execute_End();
            }
            return PicFilePath;
        }

        #region flv文件转换图片
        //fileName flv文件地址
        //imgFile 输出的图片地址
        public static string CatchFLVImg(string fileName, string imgFile)
        {
            string ffmpeg = "/VeryManage/SwfDll/ffmpeg.exe"; //ffmpeg执行文件的路径

            string flv_img = imgFile + ".jpg";

            string FlvImgSize = (150 * 110).ToString();//生成的图片分辨率 240x180

            System.Diagnostics.ProcessStartInfo ImgstartInfo = new System.Diagnostics.ProcessStartInfo(ffmpeg);
            ImgstartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

            ImgstartInfo.Arguments = "   -i   " + fileName + "  -y  -f  image2   -ss 2 -vframes 1  -s   " + FlvImgSize + "   " + flv_img;
            try
            {
                System.Diagnostics.Process.Start(ImgstartInfo);
            }
            catch
            {
                return "";
            }
            if (System.IO.File.Exists(flv_img))
            {
                return flv_img;
            }

            return "";
        }
        #endregion


        /// <summary>
        /// 仿照上传图片上传视频
        /// </summary>
        /// <param name="PostedFile">图片地址</param>
        /// <param name="FolderName">文件夹名称</param>
        /// <returns></returns>
        public static string UploadFile1(System.Web.HttpPostedFile PostedFile, string FolderName)
        {
            //Web.config里设置路径到..\Upload\"/>

            //string configdir = System.Configuration.ConfigurationManager.AppSettings["UploadDir"].ToString();
            string configdir = "/Files";
            configdir = HttpContext.Current.Request.MapPath(configdir);
            //获取当前时间
            DateTime dt = DateTime.Now;
            //创建FolderName文件夹
            if (FolderName != "" && FolderName != null)
                configdir = configdir + "\\" + FolderName;
            DirectoryInfo doci = new DirectoryInfo(configdir);
            if (!doci.Exists)
            {
                doci.Create();
            }
            //生成年文件
            string YearFile = configdir + "\\" + dt.Year.ToString();
            DirectoryInfo docy = new DirectoryInfo(YearFile);
            if (!docy.Exists)
            {
                docy.Create();
            }
            //生成月文件
            string MonthFile = YearFile + "\\" + dt.Month.ToString() + "\\";
            DirectoryInfo docm = new DirectoryInfo(MonthFile);
            if (!docm.Exists)
            {
                docm.Create();
            }

            string AllPath = "";

            //if (PostedFile != null)
            //{//Mediaplayer/.avi .mpg .mpeg .wmv .wma .asf .mid .mp3 / Realplay/ .rm .ram .rmvb/  Quicktime/.mov .amr .3gp/
            string oldname = System.IO.Path.GetFileName(PostedFile.FileName);

            //将名称重命名

            // string oldname1= oldname.Substring(0,oldname.LastIndexOf(".")-1);

            int length = oldname.Length - oldname.LastIndexOf(".");//strname.Length - strname.LastIndexOf("\\");
            string name = oldname.Substring(oldname.LastIndexOf("."), length);

            //if (PostedFile.ContentType != "application/msword" && PostedFile.ContentType != "text/html" && PostedFile.ContentType != "application/pdf" && PostedFile.ContentType != "application/vnd.ms-powerpoint" && PostedFile.ContentType != "application/vnd.ms-excel" && PostedFile.ContentType != "text/xml" && PostedFile.ContentType != "text/plain" && PostedFile.ContentType != "application/vnd.openxmlformats-officedocument.wordprocessingml.document" && PostedFile.ContentType != "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" && PostedFile.ContentType != "application/x-zip-compressed")
            //{
            //    Prompts("文件类型错误,只能上传doc/html/pdf/ppt/xls/xml/txt格式的文件! ", GetCurrentUrl());
            //}

            // string filename = DateTime.Now.ToString("yyyy_MM_ddhhmmss_") + oldname;
            string filename = Guid.NewGuid().ToString() + name;// select newid()
            //if (PostedFile.ContentLength > 600000000)//2097152*300
            //    Prompts("文件大小超过600MB! ", GetCurrentUrl());
            //this.RegisterStartupScript("alert", "<script language=\"javascript\">alert('文件大小超过2M!');document.location=(\"" + GetCurrentUrl + "\");</script>");
            //保存图片
            try
            {
                //  Prompts("视频上传时间稍长，请耐心等待........");
                PostedFile.SaveAs(MonthFile + filename);
            }
            catch (Exception ex)
            {
                throw new Exception("上传失败!" + ex.Message);
            }

            string uploaddir = DateTime.Now.Year.ToString() + "/" + DateTime.Now.Month.ToString() + "/";
            if (FolderName != "")
                FolderName = FolderName + "/";
            AllPath = "/Files" + FolderName + uploaddir + filename;
            //}
            //else
            //    throw new Exception("上传图片不能为空!");
            return AllPath;
        }


        public static string UploadFileWord(System.Web.HttpPostedFile PostedFile, string FolderName)
        {
            //Web.config里设置路径到..\Upload\"/>

            //string configdir = System.Configuration.ConfigurationManager.AppSettings["UploadDir"].ToString();
            string configdir = "WebSite/UpLoad";
            configdir = HttpContext.Current.Request.MapPath(configdir);
            //获取当前时间
            DateTime dt = DateTime.Now;
            //创建FolderName文件夹
            if (FolderName != "" && FolderName != null)
                configdir = configdir + "\\" + FolderName;
            DirectoryInfo doci = new DirectoryInfo(configdir);
            if (!doci.Exists)
            {
                doci.Create();
            }
            //生成年文件
            string YearFile = configdir + "\\" + dt.Year.ToString();
            DirectoryInfo docy = new DirectoryInfo(YearFile);
            if (!docy.Exists)
            {
                docy.Create();
            }
            //生成月文件
            string MonthFile = YearFile + "\\" + dt.Month.ToString() + "\\";
            DirectoryInfo docm = new DirectoryInfo(MonthFile);
            if (!docm.Exists)
            {
                docm.Create();
            }

            string AllPath = "";

            //if (PostedFile != null)
            //{//Mediaplayer/.avi .mpg .mpeg .wmv .wma .asf .mid .mp3 / Realplay/ .rm .ram .rmvb/  Quicktime/.mov .amr .3gp/
            string oldname = System.IO.Path.GetFileName(PostedFile.FileName);

            //将名称重命名

            // string oldname1= oldname.Substring(0,oldname.LastIndexOf(".")-1);

            int length = oldname.Length - oldname.LastIndexOf(".");//strname.Length - strname.LastIndexOf("\\");
            string name = oldname.Substring(oldname.LastIndexOf("."), length);

            if (PostedFile.ContentType != "application/msword" && PostedFile.ContentType != "text/html" && PostedFile.ContentType != "application/pdf" && PostedFile.ContentType != "application/vnd.ms-powerpoint" && PostedFile.ContentType != "application/vnd.ms-excel" && PostedFile.ContentType != "text/xml" && PostedFile.ContentType != "text/plain" && PostedFile.ContentType != "application/vnd.openxmlformats-officedocument.wordprocessingml.document" && PostedFile.ContentType != "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" && PostedFile.ContentType != "application/x-zip-compressed")
            {
                Prompts("文件类型错误,只能上传doc/html/pdf/ppt/xls/xml/txt格式的文件! ", GetCurrentUrl());
                //this.RegisterStartupScript("alert", "<script language=\"javascript\">alert('文件类型错误');document.location=(\"" + GetCurrentUrl + "\");</script>");
            }

            // string filename = DateTime.Now.ToString("yyyy_MM_ddhhmmss_") + oldname;
            string filename = Guid.NewGuid().ToString() + name;// select newid()
            //if (PostedFile.ContentLength > 600000000)//2097152*300
            //    Prompts("文件大小超过600MB! ", GetCurrentUrl());
            //this.RegisterStartupScript("alert", "<script language=\"javascript\">alert('文件大小超过2M!');document.location=(\"" + GetCurrentUrl + "\");</script>");
            //保存图片
            try
            {
                //  Prompts("视频上传时间稍长，请耐心等待........");
                PostedFile.SaveAs(MonthFile + filename);
            }
            catch (Exception ex)
            {
                throw new Exception("上传失败!" + ex.Message);
            }

            string uploaddir = DateTime.Now.Year.ToString() + "/" + DateTime.Now.Month.ToString() + "/";
            if (FolderName != "")
                FolderName = FolderName + "/";
            AllPath = "../../Upload/" + FolderName + uploaddir + filename;
            //}
            //else
            //    throw new Exception("上传图片不能为空!");
            return AllPath;
        }
        /// <summary>
        /// 仿照上传图片上传视频
        /// </summary>
        /// <param name="PostedFile">图片地址</param>
        /// <param name="FolderName">文件夹名称</param>
        /// <returns></returns>
        public static string UploadFileZicaidan(System.Web.HttpPostedFile PostedFile, string FolderName)
        {
            //Web.config里设置路径到..\Upload\"/>

            //string configdir = System.Configuration.ConfigurationManager.AppSettings["UploadDir"].ToString();
            string configdir = "../UpLoad";
            configdir = HttpContext.Current.Request.MapPath(configdir);
            //获取当前时间
            DateTime dt = DateTime.Now;
            //创建FolderName文件夹
            if (FolderName != "" && FolderName != null)
                configdir = configdir + "\\" + FolderName;
            DirectoryInfo doci = new DirectoryInfo(configdir);
            if (!doci.Exists)
            {
                doci.Create();
            }
            //生成年文件
            string YearFile = configdir + "\\" + dt.Year.ToString();
            DirectoryInfo docy = new DirectoryInfo(YearFile);
            if (!docy.Exists)
            {
                docy.Create();
            }
            //生成月文件
            string MonthFile = YearFile + "\\" + dt.Month.ToString() + "\\";
            DirectoryInfo docm = new DirectoryInfo(MonthFile);
            if (!docm.Exists)
            {
                docm.Create();
            }

            string AllPath = "";

            //if (PostedFile != null)
            //{//Mediaplayer/.avi .mpg .mpeg .wmv .wma .asf .mid .mp3 / Realplay/ .rm .ram .rmvb/  Quicktime/.mov .amr .3gp/
            string oldname = System.IO.Path.GetFileName(PostedFile.FileName);

            //将名称重命名

            // string oldname1= oldname.Substring(0,oldname.LastIndexOf(".")-1);

            int length = oldname.Length - oldname.LastIndexOf(".");//strname.Length - strname.LastIndexOf("\\");
            string name = oldname.Substring(oldname.LastIndexOf("."), length);

            if (PostedFile.ContentType != "application/msword" && PostedFile.ContentType != "text/html" && PostedFile.ContentType != "application/pdf" && PostedFile.ContentType != "application/vnd.ms-powerpoint" && PostedFile.ContentType != "application/vnd.ms-excel" && PostedFile.ContentType != "text/xml" && PostedFile.ContentType != "text/plain" && PostedFile.ContentType != "application/x-zip-compressed")
            {
                Prompts("文件类型错误,只能上传doc/html/pdf/ppt/xls/xml/txt格式的文件! ", GetCurrentUrl());
                //this.RegisterStartupScript("alert", "<script language=\"javascript\">alert('文件类型错误');document.location=(\"" + GetCurrentUrl + "\");</script>");
            }

            // string filename = DateTime.Now.ToString("yyyy_MM_ddhhmmss_") + oldname;
            string filename = Guid.NewGuid().ToString() + name;// select newid()
            //if (PostedFile.ContentLength > 600000000)//2097152*300
            //    Prompts("文件大小超过600MB! ", GetCurrentUrl());
            //this.RegisterStartupScript("alert", "<script language=\"javascript\">alert('文件大小超过2M!');document.location=(\"" + GetCurrentUrl + "\");</script>");
            //保存图片
            try
            {
                //  Prompts("视频上传时间稍长，请耐心等待........");
                PostedFile.SaveAs(MonthFile + filename);
            }
            catch (Exception ex)
            {
                throw new Exception("上传失败!" + ex.Message);
            }

            string uploaddir = DateTime.Now.Year.ToString() + "/" + DateTime.Now.Month.ToString() + "/";
            if (FolderName != "")
                FolderName = FolderName + "/";
            AllPath = "../../Upload/" + FolderName + uploaddir + filename;
            //}
            //else
            //    throw new Exception("上传图片不能为空!");
            return AllPath;
        }

        /// <summary>
        /// 仿照上传图片
        /// </summary>
        /// <param name="PostedFile">图片地址</param>
        /// <param name="FolderName">文件夹名称</param>
        /// <returns></returns>
        public static string UploadFileImage(System.Web.HttpPostedFile PostedFile, string FolderName)
        {
            //Web.config里设置路径到..\Upload\"/>

            //string configdir = System.Configuration.ConfigurationManager.AppSettings["UploadDir"].ToString();
            string configdir = "";
            if (FolderName == "Lanmutupian" || FolderName == "Youqinglianjie" || FolderName == "DingbuLogo" || FolderName == "LanmuZhengwentupian")
            {
                configdir = "../../VeryManage/UpLoad";
            }
            else
            {
                configdir = "../UpLoad";
            }
            configdir = HttpContext.Current.Request.MapPath(configdir);
            //获取当前时间
            DateTime dt = DateTime.Now;
            //创建FolderName文件夹
            if (FolderName != "" && FolderName != null)
                configdir = configdir + "\\" + FolderName;
            DirectoryInfo doci = new DirectoryInfo(configdir);
            if (!doci.Exists)
            {
                doci.Create();
            }
            //生成年文件
            string YearFile = configdir + "\\" + dt.Year.ToString();
            DirectoryInfo docy = new DirectoryInfo(YearFile);
            if (!docy.Exists)
            {
                docy.Create();
            }
            //生成月文件
            string MonthFile = YearFile + "\\" + dt.Month.ToString() + "\\";
            DirectoryInfo docm = new DirectoryInfo(MonthFile);
            if (!docm.Exists)
            {
                docm.Create();
            }

            string AllPath = "";

            //if (PostedFile != null)
            //{//Mediaplayer/.avi .mpg .mpeg .wmv .wma .asf .mid .mp3 / Realplay/ .rm .ram .rmvb/  Quicktime/.mov .amr .3gp/
            string oldname = System.IO.Path.GetFileName(PostedFile.FileName);

            //将名称重命名

            // string oldname1= oldname.Substring(0,oldname.LastIndexOf(".")-1);

            int length = oldname.Length - oldname.LastIndexOf(".");//strname.Length - strname.LastIndexOf("\\");
            string name = oldname.Substring(oldname.LastIndexOf("."), length);

            if (PostedFile.ContentType != "image/gif" && PostedFile.ContentType != "image/jpeg" && PostedFile.ContentType != "image/pjpeg" && PostedFile.ContentType != "image/png" && PostedFile.ContentType != "application/x-bmp")
            {
                Prompts("文件类型错误,只能上传gif/png/jpg/bmp格式! ", GetCurrentUrl());
                //this.RegisterStartupScript("alert", "<script language=\"javascript\">alert('文件类型错误');document.location=(\"" + GetCurrentUrl + "\");</script>");
            }
            // string filename = DateTime.Now.ToString("yyyy_MM_ddhhmmss_") + oldname;
            string filename = Guid.NewGuid().ToString() + name;// select newid()
            //if (PostedFile.ContentLength > 600000000)//2097152*300
            //    Prompts("文件大小超过600MB! ", GetCurrentUrl());
            //this.RegisterStartupScript("alert", "<script language=\"javascript\">alert('文件大小超过2M!');document.location=(\"" + GetCurrentUrl + "\");</script>");
            //保存图片
            try
            {
                //  Prompts("视频上传时间稍长，请耐心等待........");
                PostedFile.SaveAs(MonthFile + filename);
            }
            catch (Exception ex)
            {
                throw new Exception("上传失败!" + ex.Message);
            }

            string uploaddir = DateTime.Now.Year.ToString() + "/" + DateTime.Now.Month.ToString() + "/";

            string path1 = "";
            if (FolderName == "Lanmutupian" || FolderName == "Youqinglianjie" || FolderName == "DingbuLogo" || FolderName == "LanmuZhengwentupian")
            {
                path1 = "../../VeryManage/UpLoad/";
            }
            else
            {
                path1 = "../UpLoad/";
            }
            if (FolderName != "")
                FolderName = FolderName + "/";
            AllPath = path1 + FolderName + uploaddir + filename;
            //}
            //else
            //    throw new Exception("上传图片不能为空!");
            return AllPath;
        }


        public static string GetCurrentUrl()
        {
            return System.Web.HttpContext.Current.Request.Url.PathAndQuery;
        }
        //物理删除图片
        public static bool Del_MapPath(string PicPath)
        {
            if (!string.IsNullOrEmpty(PicPath))
            {
                //string newpath = HttpContext.Current.Server.MapPath(PicPath);

                string newpath = HttpContext.Current.Request.MapPath(PicPath);

                if (File.Exists(newpath))
                {
                    File.Delete(newpath);
                    return true;
                }
                else
                {

                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        //指定返回页面提示框
        public static void Prompts(string message, string url)
        {
            string str = "";
            str = "<script language='javascript'>{";
            str += "alert('" + message + "');location.href='" + url + "';";
            str += "}</script>";
            System.Web.HttpContext.Current.Response.Write(str);
            System.Web.HttpContext.Current.Response.End();
        }
        //返回上一页提示框
        public static void Prompts(string message)
        {
            string str = "";
            str = "<script language='javascript'>{";
            str += "alert('" + message + "');history.go(-1);";
            str += "}</script>";
            System.Web.HttpContext.Current.Response.Write(str);
            System.Web.HttpContext.Current.Response.End();
        }
        //返回上一页提示框(无跳转)
        public void Prompts(string message, int id)
        {
            string str = "";
            str = "<script language='javascript'>{";
            str += "alert('" + message + "');";
            str += "}</script>";
        }

        #endregion

        public static string GetQueryStringInt(string strIn)
        {
            if (string.IsNullOrEmpty(strIn))
            {

                return "";
            }
            return Regex.Replace(strIn.Trim(), @"[^\d]", "");
        }
        public static string GetQueryStringChar(string strIn)
        {
            if (string.IsNullOrEmpty(strIn))
            {

                return "";
            }
            return Regex.Replace(strIn.Trim(), @"[^\w]", "");
        }
        public static string FilterScript(string content)
        {
            string commentPattern = @"(?'comment'<!--.*?--[ \n\r]*>)";
            string embeddedScriptComments = @"(\/\*.*?\*\/|\/\/.*?[\n\r])";
            string scriptPattern = String.Format(@"(?'script'<[ \n\r]*script[^>]*>(.*?{0}?)*<[ \n\r]*/script[^>]*>)", embeddedScriptComments);
            // 包含注释和Script语句
            string pattern = String.Format(@"(?s)({0}|{1})", commentPattern, scriptPattern);

            return StripScriptAttributesFromTags(Regex.Replace(content, pattern, string.Empty, RegexOptions.IgnoreCase));
        }

        private static string StripScriptAttributesFromTags(string content)
        {
            string eventAttribs = @"on(blur|c(hange|lick)|dblclick|focus|keypress|(key|mouse)(down|up)|(un)?load
                    |mouse(move|o(ut|ver))|reset|s(elect|ubmit))";

            string pattern = String.Format(@"(?inx)\<(\w )\s((?'attribute'(?'attributeName'{0})\s*=\s*(?'delim'['""]?)(?'attributeValue'[^'"">] )(\3))|(?'attribute'(?'attributeName'href)\s*=\s*(?'delim'['""]?)(?'attributeValue'javascript[^'"">] )(\3))|[^>])*\>", eventAttribs);
            Regex re = new Regex(pattern);
            // 使用MatchEvaluator的委托
            return re.Replace(content, new MatchEvaluator(StripAttributesHandler));
        }

        private static string StripAttributesHandler(Match m)
        {
            if (m.Groups["attribute"].Success)
            {
                return m.Value.Replace(m.Groups["attribute"].Value, "");
            }
            else
            {
                return m.Value;
            }
        }

        public static string FilterAHrefScript(string content)
        {
            string newstr = FilterScript(content);
            string regexstr = @" href[ ^=]*= *[\s\S]*script *:";
            return Regex.Replace(newstr, regexstr, string.Empty, RegexOptions.IgnoreCase);
        }

        public static string FilterSrc(string content)
        {
            string newstr = FilterScript(content);
            string regexstr = @" src *= *['""]?[^\.] \.(js|vbs|asp|aspx|php|jsp)['""]";
            return Regex.Replace(newstr, regexstr, @"", RegexOptions.IgnoreCase);
        }

        public static string FilterImg(string content)
        {
            string newstr = string.Empty; //FilterScript(content);
            Regex r = new Regex(@"<img\s+[^>]*\s*src\s*=\s*([']?)(?<url>\S+)'?[^>]*>",
        RegexOptions.Compiled);
            //bmp,jpg,tiff,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw
            newstr = Regex.Replace(content, r.ToString(), @"", RegexOptions.IgnoreCase);

            //Match m = r.Match(content.ToLower());
            //if (m.Success)
            //    newstr = m.Result("${url}");
            newstr = newstr.Replace("\"", "");
            return newstr;
        }


        public static string FilterInclude(string content)
        {
            string newstr = FilterScript(content);
            string regexstr = @"<[\s\S]*include *(file|virtual) *= *[\s\S]*\.(js|vbs|asp|aspx|php|jsp)[^>]*>";
            return Regex.Replace(newstr, regexstr, string.Empty, RegexOptions.IgnoreCase);
        }

        public static string FilterHtml(string content)
        {
            string newstr = FilterScript(content);
            string regexstr = @"<[^>]*>";
            return Regex.Replace(newstr, regexstr, string.Empty, RegexOptions.IgnoreCase);
        }

        public static string FilterObject(string content)
        {
            string regexstr = @"(?i)<Object([^>])*>(\w|\W)*</Object([^>])*>";
            return Regex.Replace(content, regexstr, string.Empty, RegexOptions.IgnoreCase);
        }

        public static string FilterIframe(string content)
        {
            string regexstr = @"(?i)<Iframe([^>])*>(\w|\W)*</Iframe([^>])*>";
            return Regex.Replace(content, regexstr, string.Empty, RegexOptions.IgnoreCase);
        }

        public static string FilterFrameset(string content)
        {
            string regexstr = @"(?i)<Frameset([^>])*>(\w|\W)*</Frameset([^>])*>";
            return Regex.Replace(content, regexstr, string.Empty, RegexOptions.IgnoreCase);
        }

        //移除非法或不友好字符
        private static string FilterBadWords(string chkStr)
        {
            //这里的非法和不友好字符由你任意加，用“|”分隔，支持正则表达式,由于本Blog禁止贴非法和不友好字符，所以这里无法加上。
            string BadWords = @"";
            if (chkStr == "")
            {
                return "";
            }

            string[] bwords = BadWords.Split('#');
            int i, j;
            string str;
            StringBuilder sb = new StringBuilder();
            for (i = 0; i < bwords.Length; i++)
            {
                str = bwords[i].ToString().Trim();
                string regStr, toStr;
                regStr = str;
                Regex r = new Regex(regStr, RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline);
                Match m = r.Match(chkStr);
                if (m.Success)
                {
                    j = m.Value.Length;
                    sb.Insert(0, "*", j);
                    toStr = sb.ToString();
                    chkStr = Regex.Replace(chkStr, regStr, toStr, RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline);
                }
                sb.Remove(0, sb.Length);
            }
            return chkStr;
        }
        public static string ClearScript(string strIn)
        {
            if (string.IsNullOrEmpty(strIn))
            {
                return "";
            }

            string content = strIn;
            content = FilterScript(content);
            content = FilterAHrefScript(content);
            //content = FilterObject(content);
            content = FilterIframe(content);
            content = FilterFrameset(content);
            content = FilterSrc(content);
            content = FilterInclude(content);
            return content;

        }
        public static string ClearHtml(string Htmlstring)
        {
            if (Htmlstring != "")
            {
                Regex r = null;
                Match m = null;

                r = new Regex(@"<\/?[^>]*>", RegexOptions.IgnoreCase);
                for (m = r.Match(Htmlstring); m.Success; m = m.NextMatch())
                {
                    Htmlstring = Htmlstring.Replace(m.Groups[0].ToString(), "");
                }
            }

            //删除脚本

            Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);

            //删除HTML

            Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);



            Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);

            Htmlstring.Replace("<", "");

            Htmlstring.Replace(">", "");

            Htmlstring.Replace("\r\n", "");

            //Htmlstring =System.Web.HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
            return Htmlstring;
        }
        public static string UnSafeStringEncode(string strIn)
        {

            if (string.IsNullOrEmpty(strIn))
            {

                return "";
            }
            strIn = FilterSrc(strIn);

            strIn = strIn.Replace("&", "&amp;");

            strIn = strIn.Replace("select", "sel&#101;ct");
            strIn = strIn.Replace("join", "jo&#105;n");
            strIn = strIn.Replace("union", "un&#105;on");
            strIn = strIn.Replace("where", "wh&#101;re");
            strIn = strIn.Replace("insert", "ins&#101;rt");
            strIn = strIn.Replace("delete", "del&#101;te");
            strIn = strIn.Replace("update", "up&#100;ate");
            strIn = strIn.Replace("like", "lik&#101;");
            strIn = strIn.Replace("drop", "dro&#112;");
            strIn = strIn.Replace("create", "cr&#101;ate");
            strIn = strIn.Replace("modify", "mod&#105;fy");
            strIn = strIn.Replace("rename", "ren&#097;me");
            strIn = strIn.Replace("alter", "alt&#101;r");
            strIn = strIn.Replace("cast", "ca&#115;t");
            strIn = strIn.Replace("script", "scr&#105;pt");
            strIn = strIn.Replace("src", "&#115;rc");

            strIn = strIn.Replace("\"", "&quot;");
            strIn = strIn.Replace(">", "&gt;");
            strIn = strIn.Replace("<", "&lt;");
            strIn = strIn.Replace(" ", "&nbsp;");
            strIn = strIn.Replace("'", "&#39;");

            return strIn;
        }

        public static string UnSafeStringEncode1(string strIn)
        {
            if (string.IsNullOrEmpty(strIn))
            {
                return "";
            }
            FilterHtml(strIn);
            // strIn = FilterSrc(strIn);
            strIn = strIn.Replace("&", "&amp;");
            strIn = strIn.Replace("select", "sel&#101;ct");
            strIn = strIn.Replace("join", "jo&#105;n");
            strIn = strIn.Replace("union", "un&#105;on");
            strIn = strIn.Replace("where", "wh&#101;re");
            strIn = strIn.Replace("insert", "ins&#101;rt");
            strIn = strIn.Replace("delete", "del&#101;te");
            strIn = strIn.Replace("update", "up&#100;ate");
            strIn = strIn.Replace("like", "lik&#101;");
            strIn = strIn.Replace("drop", "dro&#112;");
            strIn = strIn.Replace("create", "cr&#101;ate");
            strIn = strIn.Replace("modify", "mod&#105;fy");
            strIn = strIn.Replace("rename", "ren&#097;me");
            strIn = strIn.Replace("alter", "alt&#101;r");
            strIn = strIn.Replace("cast", "ca&#115;t");
            strIn = strIn.Replace("script", "scr&#105;pt");
            return strIn;
        }

        public static string UnSafeStringDecode1(string strIn)
        {

            if (string.IsNullOrEmpty(strIn))
            {
                return "";
            }

            strIn = strIn.Replace("sel&#101;ct", "select");
            strIn = strIn.Replace("jo&#105;n", "join");
            strIn = strIn.Replace("un&#105;on", "union");
            strIn = strIn.Replace("wh&#101;re", "where");
            strIn = strIn.Replace("ins&#101;rt", "insert");
            strIn = strIn.Replace("del&#101;te", "delete");
            strIn = strIn.Replace("up&#100;ate", "update");
            strIn = strIn.Replace("lik&#101;", "like");
            strIn = strIn.Replace("dro&#112;", "drop");
            strIn = strIn.Replace("cr&#101;ate", "create");
            strIn = strIn.Replace("mod&#105;fy", "modify");
            strIn = strIn.Replace("ren&#097;me", "rename");
            strIn = strIn.Replace("alt&#101;r", "alter");
            strIn = strIn.Replace("ca&#115;t", "cast");
            strIn = strIn.Replace("scr&#105;pt", "script");

            strIn = strIn.Replace("&amp;", "&");

            return strIn;
        }
        public static string UnSafeStringDecode(string strIn)
        {

            if (string.IsNullOrEmpty(strIn))
            {
                return "";
            }

            strIn = strIn.Replace("&quot;", "\"");
            strIn = strIn.Replace("&gt;", ">");
            strIn = strIn.Replace("&lt;", "<");
            strIn = strIn.Replace("&nbsp;", " ");
            strIn = strIn.Replace("&#39;", "'");

            strIn = strIn.Replace("sel&#101;ct", "select");
            strIn = strIn.Replace("jo&#105;n", "join");
            strIn = strIn.Replace("un&#105;on", "union");
            strIn = strIn.Replace("wh&#101;re", "where");
            strIn = strIn.Replace("ins&#101;rt", "insert");
            strIn = strIn.Replace("del&#101;te", "delete");
            strIn = strIn.Replace("up&#100;ate", "update");
            strIn = strIn.Replace("lik&#101;", "like");
            strIn = strIn.Replace("dro&#112;", "drop");
            strIn = strIn.Replace("cr&#101;ate", "create");
            strIn = strIn.Replace("mod&#105;fy", "modify");
            strIn = strIn.Replace("ren&#097;me", "rename");
            strIn = strIn.Replace("alt&#101;r", "alter");
            strIn = strIn.Replace("ca&#115;t", "cast");
            strIn = strIn.Replace("scr&#105;pt", "script");
            strIn = strIn.Replace("&#115;rc", "src");

            strIn = strIn.Replace("&amp;", "&");

            return strIn;
        }



        /// <summary>
        /// 根据域名反Ping出IP
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetIPByDomain(string url)
        {
            if (url.Trim() == string.Empty)
                return "";
            try
            {
                System.Net.IPHostEntry host = System.Net.Dns.GetHostEntry(url);
                return host.AddressList.GetValue(0).ToString();
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        public static string GetClientIP()
        {
            string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (null == result || result == String.Empty)
            {
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }

            if (null == result || result == String.Empty)
            {
                result = HttpContext.Current.Request.UserHostAddress;
            }
            return result;
        }
        /// <summary>
        /// 获得当前绝对路径
        /// </summary>
        /// <param name="strPath">指定的路径</param>
        /// <returns>绝对路径</returns>
        public static string GetMapPath(string strPath)
        {
            if (HttpContext.Current != null)
            {
                return HttpContext.Current.Server.MapPath(strPath);
            }
            else //非web程序引用
            {
                return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
            }
        }


        public static Regex _pathComponentTextToEscape = new Regex(@"([^A-Za-z0-9\- ]+|\.| )", RegexOptions.Singleline | RegexOptions.Compiled);
        public static Regex _pathComponentTextToUnescape = new Regex(@"((?:_(?:[0-9a-f][0-9a-f][0-9a-f][0-9a-f])+_)|\+)", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);
        public static Regex _fileComponentTextToEscape = new Regex(@"([^A-Za-z0-9 ]+|\.| )", RegexOptions.Singleline | RegexOptions.Compiled);
        public static Regex _fileComponentTextToUnescape = new Regex(@"((?:_(?:[0-9a-f][0-9a-f][0-9a-f][0-9a-f])+_)|_|\-)", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);

        /// <summary>
        /// Adds a string to the current url determining the correct seperator character
        /// </summary>
        /// <param name="url"></param>
        /// <param name="querystring"></param>
        /// <returns></returns>
        public static string AppendQuerystring(string url, string querystring)
        {
            return AppendQuerystring(url, querystring, false);
        }
        public static string AppendQuerystring(string url, string querystring, bool urlEncoded)
        {
            string seperator = "?";
            if (url.IndexOf('?') > -1)
            {
                if (!urlEncoded)
                    seperator = "&";
                else
                    seperator = "&amp;";
            }
            return string.Concat(url, seperator, querystring);
        }

        static public string ApplicationPath
        {

            get
            {
                string applicationPath = "/";

                if (HttpContext.Current != null)
                    applicationPath = HttpContext.Current.Request.ApplicationPath;

                // Are we in an application?
                //
                if (applicationPath == "/")
                {
                    return string.Empty;
                }
                else
                {
                    return applicationPath;
                }
            }

        }

        /// <summary>
        /// Converts a prepared subject line back into a raw text subject line.
        /// </summary>
        /// <param name="textToFormat">The prepared subject line.</param>
        /// <returns>A raw text subject line.</returns>
        /// <remarks>This function is only needed when editing an existing message or when replying to
        /// a message - it turns the HTML escaped characters back into their pre-escaped status.</remarks>
        public static string HtmlDecode(String textToFormat)
        {
            if (ValueUtils.IsNullorEmpty(textToFormat))
                return textToFormat;

            //ScottW: Removed Context dependency
            return System.Web.HttpUtility.HtmlDecode(textToFormat);
            // strip the HTML - i.e., turn < into &lt;, > into &gt;
            //return HttpContext.Current.Server.HtmlDecode(FormattedMessageSubject);
        }

        /// <summary>
        /// Converts a prepared subject line back into a raw text subject line.
        /// </summary>
        /// <param name="textToFormat">The prepared subject line.</param>
        /// <returns>A raw text subject line.</returns>
        /// <remarks>This function is only needed when editing an existing message or when replying to
        /// a message - it turns the HTML escaped characters back into their pre-escaped status.</remarks>
        public static string HtmlEncode(String textToFormat)
        {
            // strip the HTML - i.e., turn < into &lt;, > into &gt;

            if (ValueUtils.IsNullorEmpty(textToFormat))
                return textToFormat;

            //ScottW: Removed Context dependency
            return System.Web.HttpUtility.HtmlEncode(textToFormat);
            //return HttpContext.Current.Server.HtmlEncode(FormattedMessageSubject);
        }

        public static string UrlEncode(string urlToEncode)
        {
            if (ValueUtils.IsNullorEmpty(urlToEncode))
                return urlToEncode;

            return System.Web.HttpUtility.UrlEncode(urlToEncode).Replace("'", "%27");
            ;
        }

        public static string UrlDecode(string urlToDecode)
        {
            if (ValueUtils.IsNullorEmpty(urlToDecode))
                return urlToDecode;

            return System.Web.HttpUtility.UrlDecode(urlToDecode);
        }

        public static string UrlEncodePathComponent(string text)
        {
            return UrlEncode(text, _pathComponentTextToEscape, '+', '_');
        }

        public static string UrlDecodePathComponent(string text)
        {
            return UrlDecode(text, _pathComponentTextToUnescape);
        }

        public static string UrlEncodeFileComponent(string text)
        {
            return UrlEncode(text, _fileComponentTextToEscape, '-', '_');
        }

        public static string UrlDecodeFileComponent(string text)
        {
            return UrlDecode(text, _fileComponentTextToUnescape);
        }

        private static string UrlEncode(string text, Regex pattern, char spaceReplacement, char escapePrefix)
        {
            if (ValueUtils.IsNullorEmpty(text))
                return text;

            Match match = pattern.Match(text);
            StringBuilder encText = new StringBuilder();
            int lastEndIndex = 0;
            while (match.Value != string.Empty)
            {
                if (lastEndIndex != match.Index)
                    encText.Append(text.Substring(lastEndIndex, match.Index - lastEndIndex));

                if (match.Value == " ")
                    encText.Append(spaceReplacement);
                else if (match.Value == "." && match.Index != text.Length - 1)
                    encText.Append("."); // . at the end of text causes a 404... only encode . at the end of text
                else
                {
                    encText.Append(escapePrefix);
                    byte[] bytes = Encoding.Unicode.GetBytes(match.Value);
                    if (bytes != null)
                    {
                        foreach (byte b in bytes)
                        {
                            string hexByte = b.ToString("X");

                            if (hexByte.Length == 1)
                                encText.Append("0");

                            encText.Append(hexByte);
                        }
                    }
                    encText.Append(escapePrefix);
                }

                lastEndIndex = match.Index + match.Length;
                match = pattern.Match(text, lastEndIndex);
            }

            if (lastEndIndex < text.Length)
                encText.Append(text.Substring(lastEndIndex));

            return encText.ToString();
        }

        private static string UrlDecode(string text, Regex pattern)
        {
            if (ValueUtils.IsNullorEmpty(text))
                return text;

            Match match = pattern.Match(text);
            StringBuilder decText = new StringBuilder();
            int lastEndIndex = 0;
            while (match.Value != string.Empty)
            {
                if (lastEndIndex != match.Index)
                    decText.Append(text.Substring(lastEndIndex, match.Index - lastEndIndex));

                if (match.Value.Length == 1)
                    decText.Append(" ");
                else
                {
                    byte[] bytes = new byte[(match.Value.Length - 2) / 2];

                    for (int i = 1; i < match.Value.Length - 1; i += 2)
                        bytes[(i - 1) / 2] = byte.Parse(match.Value.Substring(i, 2), NumberStyles.AllowHexSpecifier);

                    decText.Append(Encoding.Unicode.GetString(bytes));
                }

                lastEndIndex = match.Index + match.Length;
                match = pattern.Match(text, lastEndIndex);
            }

            if (lastEndIndex < text.Length)
                decText.Append(text.Substring(lastEndIndex));

            return decText.ToString();
        }
    }
}
